// Viewer Script - 查看和编辑录制

class RecordingViewer {
  constructor() {
    this.recordingId = null;
    this.recording = null;
    this.isEditMode = false;
    this.originalRecording = null;
    
    // 图片预览相关状态
    this.currentImageIndex = 0;
    this.allImages = [];
    this.currentZoom = 1;
    this.minZoom = 0.25;
    this.maxZoom = 4;
    
    // DOM元素
    this.elements = {
      recordingTitle: document.getElementById('recordingTitle'),
      recordingUrl: document.getElementById('recordingUrl'),
      recordingDate: document.getElementById('recordingDate'),
      recordingDuration: document.getElementById('recordingDuration'),
      stepCount: document.getElementById('stepCount'),
      stepsContainer: document.getElementById('stepsContainer'),
      backBtn: document.getElementById('backBtn'),
      editBtn: document.getElementById('editBtn'),
      exportBtn: document.getElementById('exportBtn'),
      exportModal: document.getElementById('exportModal'),
      closeModalBtn: document.getElementById('closeModalBtn'),
      cancelExportBtn: document.getElementById('cancelExportBtn'),
      confirmExportBtn: document.getElementById('confirmExportBtn'),
      editToolbar: document.getElementById('editToolbar'),
      saveBtn: document.getElementById('saveBtn'),
      cancelEditBtn: document.getElementById('cancelEditBtn'),
      imagePreviewModal: document.getElementById('imagePreviewModal'),
      previewImage: document.getElementById('previewImage'),
      closePreview: document.getElementById('closePreview'),
      prevBtn: document.getElementById('prevBtn'),
      nextBtn: document.getElementById('nextBtn'),
      navInfo: document.getElementById('navInfo'),
      zoomInBtn: document.getElementById('zoomInBtn'),
      zoomOutBtn: document.getElementById('zoomOutBtn'),
      resetZoomBtn: document.getElementById('resetZoomBtn'),
      zoomInfo: document.getElementById('zoomInfo'),
      fullscreenBtn: document.getElementById('fullscreenBtn'),
      downloadBtn: document.getElementById('downloadBtn')
    };
    
    this.init();
  }
  
  async init() {
    // 从URL获取录制ID
    const urlParams = new URLSearchParams(window.location.search);
    this.recordingId = urlParams.get('id');
    
    if (!this.recordingId) {
      this.showError('No recording ID provided');
      return;
    }
    
    // 加载录制数据
    await this.loadRecording();
    
    // 设置事件监听器
    this.setupEventListeners();
  }
  
  async loadRecording() {
    try {
      // 获取所有录制
      const response = await chrome.runtime.sendMessage({
        action: 'GET_RECORDINGS'
      });
      
      if (!response.success) {
        throw new Error('Failed to load recordings');
      }
      
      // 找到对应的录制
      this.recording = response.recordings.find(r => r.id === this.recordingId);
      
      if (!this.recording) {
        throw new Error('Recording not found');
      }
      
      // 显示录制数据
      this.displayRecording();
      
    } catch (error) {
      console.error('Error loading recording:', error);
      this.showError('Failed to load recording');
    }
  }
  
  displayRecording() {
    // 更新标题和信息
    this.elements.recordingTitle.textContent = this.recording.title;
    this.elements.recordingUrl.href = this.recording.url || '#';
    this.elements.recordingUrl.textContent = this.recording.url || 'N/A';
    this.elements.recordingDate.textContent = this.formatDate(this.recording.startTime);
    this.elements.recordingDuration.textContent = this.calculateDuration();
    this.elements.stepCount.textContent = `${this.recording.steps.length} steps`;
    
    // 显示步骤
    this.displaySteps();
  }
  
  displaySteps() {
    if (!this.recording.steps || this.recording.steps.length === 0) {
      this.elements.stepsContainer.innerHTML = `
        <div class="empty-state">
          <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
            <rect x="16" y="16" width="32" height="32" rx="4" stroke="currentColor" stroke-width="2" stroke-dasharray="4 4"/>
            <path d="M28 32h8M32 28v8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
          <p>No steps recorded</p>
        </div>
      `;
      return;
    }
    
    this.elements.stepsContainer.innerHTML = this.recording.steps.map((step, index) => `
      <div class="step-item" data-index="${index}">
        <div class="step-header">
          <div class="step-number">${index + 1}</div>
          <div class="step-content">
            <div class="step-action">${step.action}</div>
            <div class="step-description" ${this.isEditMode ? 'contenteditable="true" class="editable"' : ''}>
              ${this.escapeHtml(step.description)}
            </div>
            ${step.selector ? `<div class="step-meta">Element: <span class="step-selector">${this.escapeHtml(step.selector)}</span></div>` : ''}
          </div>
          ${this.isEditMode ? `
            <div class="step-actions">
              <button class="step-action-btn delete" data-action="delete" data-index="${index}" title="Delete step">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path d="M2 4h12M5 4V2.5A1.5 1.5 0 016.5 1h3A1.5 1.5 0 0111 2.5V4m2 0v9.5a1.5 1.5 0 01-1.5 1.5h-7A1.5 1.5 0 013 13.5V4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </button>
            </div>
          ` : ''}
        </div>
        ${step.screenshot ? `
          <div class="step-screenshot">
            <img src="${step.screenshot}" alt="Step ${index + 1} screenshot">
          </div>
        ` : ''}
      </div>
    `).join('');
    
    // 绑定编辑模式下的事件
    if (this.isEditMode) {
      this.bindEditEvents();
    }
    
    // 绑定图片预览事件
    this.bindImagePreviewEvents();
  }
  
  setupEventListeners() {
    // 返回按钮
    if (this.elements.backBtn) {
      this.elements.backBtn.addEventListener('click', () => {
        window.close();
      });
    }
    
    // 编辑按钮
    if (this.elements.editBtn) {
      this.elements.editBtn.addEventListener('click', () => {
        this.enterEditMode();
      });
    }
    
    // 导出按钮
    if (this.elements.exportBtn) {
      this.elements.exportBtn.addEventListener('click', () => {
        this.showExportModal();
      });
    }
    
    // 导出模态框
    if (this.elements.closeModalBtn) {
      this.elements.closeModalBtn.addEventListener('click', () => {
        this.hideExportModal();
      });
    }
    
    if (this.elements.cancelExportBtn) {
      this.elements.cancelExportBtn.addEventListener('click', () => {
        this.hideExportModal();
      });
    }
    
    if (this.elements.confirmExportBtn) {
      this.elements.confirmExportBtn.addEventListener('click', () => {
        this.exportRecording();
      });
    }
    
    // 编辑工具栏
    if (this.elements.saveBtn) {
      this.elements.saveBtn.addEventListener('click', () => {
        this.saveChanges();
      });
    }
    
    if (this.elements.cancelEditBtn) {
      this.elements.cancelEditBtn.addEventListener('click', () => {
        this.exitEditMode();
      });
    }
    
    // 点击模态框背景关闭
    if (this.elements.exportModal) {
      this.elements.exportModal.addEventListener('click', (e) => {
        if (e.target === this.elements.exportModal) {
          this.hideExportModal();
        }
      });
    }
    
    // 图片预览相关事件
    this.setupImagePreviewControls();
    
    // ESC键关闭预览
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        const modal = document.getElementById('imagePreviewModal');
        if (modal && modal.classList.contains('show')) {
          this.hideImagePreview();
        }
      }
    });
  }
  
  enterEditMode() {
    this.isEditMode = true;
    this.originalRecording = JSON.parse(JSON.stringify(this.recording));
    
    // 更新UI
    this.elements.editBtn.style.display = 'none';
    this.elements.editToolbar.classList.add('show');
    
    // 使标题可编辑
    this.elements.recordingTitle.contentEditable = true;
    this.elements.recordingTitle.classList.add('editable');
    
    // 重新渲染步骤（带编辑功能）
    this.displaySteps();
  }
  
  exitEditMode() {
    if (confirm('Discard all changes?')) {
      this.isEditMode = false;
      this.recording = this.originalRecording;
      this.originalRecording = null;
      
      // 更新UI
      this.elements.editBtn.style.display = '';
      this.elements.editToolbar.classList.remove('show');
      
      // 禁用标题编辑
      this.elements.recordingTitle.contentEditable = false;
      this.elements.recordingTitle.classList.remove('editable');
      
      // 重新显示录制
      this.displayRecording();
    }
  }
  
  bindEditEvents() {
    // 删除步骤按钮
    document.querySelectorAll('[data-action="delete"]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const index = parseInt(btn.dataset.index);
        this.deleteStep(index);
      });
    });
    
    // 可编辑的描述字段
    document.querySelectorAll('.step-description.editable').forEach((el, index) => {
      el.addEventListener('blur', () => {
        this.recording.steps[index].description = el.textContent.trim();
      });
      
      // 防止换行
      el.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          el.blur();
        }
      });
    });
  }
  
  deleteStep(index) {
    if (confirm(`Delete step ${index + 1}?`)) {
      this.recording.steps.splice(index, 1);
      this.displaySteps();
    }
  }
  
  async saveChanges() {
    try {
      // 更新标题
      this.recording.title = this.elements.recordingTitle.textContent.trim();
      
      // 发送更新请求
      const response = await chrome.runtime.sendMessage({
        action: 'UPDATE_RECORDING',
        recordingId: this.recordingId,
        updates: {
          title: this.recording.title,
          steps: this.recording.steps
        }
      });
      
      if (response.success) {
        this.isEditMode = false;
        this.originalRecording = null;
        
        // 更新UI
        this.elements.editBtn.style.display = '';
        this.elements.editToolbar.classList.remove('show');
        
        // 禁用标题编辑
        this.elements.recordingTitle.contentEditable = false;
        this.elements.recordingTitle.classList.remove('editable');
        
        // 重新显示录制
        this.displayRecording();
        
        this.showNotification('Changes saved successfully', 'success');
      } else {
        throw new Error('Failed to save changes');
      }
      
    } catch (error) {
      console.error('Error saving changes:', error);
      this.showNotification('Failed to save changes', 'error');
    }
  }
  
  showExportModal() {
    this.elements.exportModal.classList.add('show');
  }
  
  hideExportModal() {
    this.elements.exportModal.classList.remove('show');
  }
  
  async exportRecording() {
    const format = document.querySelector('input[name="format"]:checked').value;
    
    try {
      await chrome.runtime.sendMessage({
        action: 'EXPORT_RECORDING',
        recording: this.recording,
        format: format,
        download: true
      });
      
      this.hideExportModal();
      this.showNotification('Recording exported successfully', 'success');
      
    } catch (error) {
      console.error('Error exporting recording:', error);
      this.showNotification('Failed to export recording', 'error');
    }
  }
  
  calculateDuration() {
    if (!this.recording.startTime || !this.recording.endTime) {
      return 'N/A';
    }
    
    const start = new Date(this.recording.startTime);
    const end = new Date(this.recording.endTime);
    const diff = end - start;
    
    const minutes = Math.floor(diff / 60000);
    const seconds = Math.floor((diff % 60000) / 1000);
    
    if (minutes > 0) {
      return `${minutes}m ${seconds}s`;
    } else {
      return `${seconds}s`;
    }
  }
  
  formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString();
  }
  
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
  
  showError(message) {
    this.elements.stepsContainer.innerHTML = `
      <div class="empty-state">
        <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
          <circle cx="32" cy="32" r="24" stroke="currentColor" stroke-width="2"/>
          <path d="M32 20v16M32 40h.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
        </svg>
        <p style="color: #dc2626;">${message}</p>
      </div>
    `;
  }
  
  showImagePreview(imageSrc, index = 0) {
    if (this.elements.previewImage && this.elements.imagePreviewModal) {
      this.currentImageIndex = index;
      this.currentZoom = 1;
      
      this.elements.previewImage.src = imageSrc;
      this.elements.previewImage.style.transform = 'scale(1)';
      this.elements.imagePreviewModal.classList.add('show');
      document.body.style.overflow = 'hidden';
      
      this.updateNavigationControls();
      this.updateZoomInfo();
    }
  }
  
  showPreviousImage() {
    if (this.currentImageIndex > 0) {
      this.currentImageIndex--;
      this.elements.previewImage.src = this.allImages[this.currentImageIndex];
      this.resetZoom();
      this.updateNavigationControls();
    }
  }
  
  showNextImage() {
    if (this.currentImageIndex < this.allImages.length - 1) {
      this.currentImageIndex++;
      this.elements.previewImage.src = this.allImages[this.currentImageIndex];
      this.resetZoom();
      this.updateNavigationControls();
    }
  }
  
  zoomIn() {
    if (this.currentZoom < this.maxZoom) {
      this.currentZoom = Math.min(this.currentZoom * 1.2, this.maxZoom);
      this.updateImageZoom();
    }
  }
  
  zoomOut() {
    if (this.currentZoom > this.minZoom) {
      this.currentZoom = Math.max(this.currentZoom / 1.2, this.minZoom);
      this.updateImageZoom();
    }
  }
  
  resetZoom() {
    this.currentZoom = 1;
    this.updateImageZoom();
  }
  
  updateImageZoom() {
    if (this.elements.previewImage) {
      this.elements.previewImage.style.transform = `scale(${this.currentZoom})`;
      
      // 当缩放大于100%时，允许图片超出容器边界
      if (this.currentZoom > 1) {
        this.elements.previewImage.classList.add('zoomed');
      } else {
        this.elements.previewImage.classList.remove('zoomed');
      }
      
      this.updateZoomInfo();
    }
  }
  
  updateNavigationControls() {
    if (this.elements.prevBtn) {
      this.elements.prevBtn.disabled = this.currentImageIndex === 0;
    }
    if (this.elements.nextBtn) {
      this.elements.nextBtn.disabled = this.currentImageIndex === this.allImages.length - 1;
    }
    if (this.elements.navInfo) {
      this.elements.navInfo.textContent = `${this.currentImageIndex + 1} / ${this.allImages.length}`;
    }
  }
  
  updateZoomInfo() {
    if (this.elements.zoomInfo) {
      this.elements.zoomInfo.textContent = `${Math.round(this.currentZoom * 100)}%`;
    }
  }
  
  toggleFullscreen() {
    if (document.fullscreenElement) {
      document.exitFullscreen();
    } else {
      this.elements.imagePreviewModal.requestFullscreen();
    }
  }
  
  downloadImage() {
    if (this.elements.previewImage && this.elements.previewImage.src) {
      const a = document.createElement('a');
      a.href = this.elements.previewImage.src;
      a.download = `scribehow-step-${this.currentImageIndex + 1}.png`;
      a.click();
    }
  }
  
  setupImagePreviewControls() {
    // 关闭按钮
    if (this.elements.closePreview) {
      this.elements.closePreview.addEventListener('click', () => this.hideImagePreview());
    }
    
    // 上一张/下一张
    if (this.elements.prevBtn) {
      this.elements.prevBtn.addEventListener('click', () => this.showPreviousImage());
    }
    if (this.elements.nextBtn) {
      this.elements.nextBtn.addEventListener('click', () => this.showNextImage());
    }
    
    // 缩放控制
    if (this.elements.zoomInBtn) {
      this.elements.zoomInBtn.addEventListener('click', () => this.zoomIn());
    }
    if (this.elements.zoomOutBtn) {
      this.elements.zoomOutBtn.addEventListener('click', () => this.zoomOut());
    }
    if (this.elements.resetZoomBtn) {
      this.elements.resetZoomBtn.addEventListener('click', () => this.resetZoom());
    }
    
    // 全屏和下载
    if (this.elements.fullscreenBtn) {
      this.elements.fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());
    }
    if (this.elements.downloadBtn) {
      this.elements.downloadBtn.addEventListener('click', () => this.downloadImage());
    }
    
    // 模态框背景点击关闭
    if (this.elements.imagePreviewModal) {
      this.elements.imagePreviewModal.addEventListener('click', (e) => {
        if (e.target === this.elements.imagePreviewModal) {
          this.hideImagePreview();
        }
      });
    }
    
    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
      if (!this.elements.imagePreviewModal || !this.elements.imagePreviewModal.classList.contains('show')) return;
      
      switch (e.key) {
        case 'Escape':
          this.hideImagePreview();
          break;
        case 'ArrowLeft':
          this.showPreviousImage();
          break;
        case 'ArrowRight':
          this.showNextImage();
          break;
        case '=':
        case '+':
          this.zoomIn();
          break;
        case '-':
          this.zoomOut();
          break;
        case '0':
          this.resetZoom();
          break;
      }
    });
    
    // 滚轮缩放功能
    if (this.elements.imagePreviewModal) {
      this.elements.imagePreviewModal.addEventListener('wheel', (e) => {
        if (!this.elements.imagePreviewModal.classList.contains('show')) return;
        
        e.preventDefault();
        
        if (e.deltaY < 0) {
          // 向上滚动 - 放大
          this.zoomIn();
        } else {
          // 向下滚动 - 缩小  
          this.zoomOut();
        }
      }, { passive: false });
    }
  }

  bindImagePreviewEvents() {
    // 收集所有截图
    this.allImages = Array.from(document.querySelectorAll('.step-screenshot img')).map(img => img.src);
    
    // 为所有截图添加点击事件
    const screenshots = document.querySelectorAll('.step-screenshot img');
    screenshots.forEach((img, index) => {
      if (!img.hasAttribute('data-preview-bound')) {
        img.style.cursor = 'pointer';
        img.setAttribute('data-preview-bound', 'true');
        img.addEventListener('click', () => {
          this.showImagePreview(img.src, index);
        });
      }
    });
  }
  
  hideImagePreview() {
    if (this.elements.imagePreviewModal) {
      this.elements.imagePreviewModal.classList.remove('show');
    }
    document.body.style.overflow = '';
  }
  
  showNotification(message, type) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 16px 24px;
      background: ${type === 'success' ? '#10b981' : '#ef4444'};
      color: white;
      border-radius: 8px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      z-index: 1000;
      animation: slideIn 0.3s ease;
    `;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 3秒后移除
    setTimeout(() => {
      notification.style.animation = 'slideOut 0.3s ease';
      setTimeout(() => notification.remove(), 300);
    }, 3000);
  }
}

// 全局变量，用于图片点击事件
let viewer;

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
  @keyframes slideIn {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }
  
  .editable {
    border: 1px solid #e5e7eb;
    padding: 4px 8px;
    border-radius: 4px;
    background: white;
    outline: none;
  }
  
  .editable:focus {
    border-color: #6366f1;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
  }
`;
document.head.appendChild(style);

// 初始化查看器
document.addEventListener('DOMContentLoaded', () => {
  viewer = new RecordingViewer();
});
